package ex.com.jm.food.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;






import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import ex.com.jm.food.entity.Admin;
import ex.com.jm.food.service.AdminService;
import ex.com.jm.food.utils.DateUtils;
import ex.com.jm.food.utils.JsonUtils;
import ex.com.jm.food.utils.MD5Utils;

/**
 * 管理员的控制层
 * @author zhaojw
 *
 */
public class AdminAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Admin admin;//管理员
	private	String vcode;//接收验证码信息
	private AdminService adminService;//业务层
	private String errorInfo;//提供错误信息
	private int initPage=1;//页码
	private int pageRow=10;//每页显示个数
	private int totalCount;//数据总量
	private String adminName;
	private Integer status;
	private String order;
	private String sort;
	private String adminId;
	private String adminEmail;
	private String adminPwd;
	public String getAdminEmail() {
		return adminEmail;
	}
	public void setAdminEmail(String adminEmail) {
		this.adminEmail = adminEmail;
	}
	public AdminService getAdminService() {
		return adminService;
	}
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}
	public Admin getAdmin() {
		return admin;
	}
	public void setAdmin(Admin admin) {
		this.admin = admin;
	}
	public String getVcode() {
		return vcode;
	}
	public void setVcode(String vcode) {
		this.vcode = vcode;
	}
	public String getErrorInfo() {
		return errorInfo;
	}
	public void setErrorInfo(String errorInfo) {
		this.errorInfo = errorInfo;
	}
	public int getInitPage() {
		return initPage;
	}
	public void setInitPage(int initPage) {
		this.initPage = initPage;
	}
	public int getPageRow() {
		return pageRow;
	}
	public void setPageRow(int pageRow) {
		this.pageRow = pageRow;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public String getAdminName() {
		return adminName;
	}
	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getAdminId() {
		return adminId;
	}
	public void setAdminId(String adminId) {
		this.adminId = adminId;
	}
	public String getAdminPwd() {
		return adminPwd;
	}
	public void setAdminPwd(String adminPwd) {
		this.adminPwd = adminPwd;
	}
	/**
	 * 到达登录页面
	 * @return
	 */
	public String login(){
		return "Index";
		
	}
	
	/**
	 * 管理员登录
	 * @return
	 */
	public String adminLogin(){
			String password=""; 
			
			try {  
				//对密码加密后在去查询
				password = MD5Utils.GetMD5Code(adminPwd);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    Admin adminLogin=adminService.adminLogin(adminEmail, password);
		    if(adminLogin!=null){
				//登录成功,将管理员信息放入session中
				 ActionContext.getContext().getSession().put("admin", adminLogin);
				 System.out.println(adminLogin.getAdminEmail());
				 return "success";
			}else {
				addFieldError("adminEmail", "用户名或密码错误，请重新输入");
				return "fail";
			}
	}
	/**
	 * 添加/修改管理员
	 * @return
	 */
	public String adminSave(){
		if(admin.getAdminName()==null||admin.getAdminName().equals("")){
			addFieldError("admin.adminName", "管理员名称不能为空");
			return "savefial";
		}else if (admin.getAdminEmail()==null||admin.getAdminEmail().equals("")) {
			addFieldError("admin.adminEmail", "管理员邮箱不能为空");
			return "savefial";
		}else if (admin.getAdminPwd()==null||admin.getAdminPwd().equals("")) {
			addFieldError("admin.adminPwd", "管理员登录密码不能为空");
			return "savefial";
		}else if (admin.getAdminPwd().length()>8||admin.getAdminPwd().length()<6) {
			addFieldError("admin.adminPwd", "管理员登录密码为6到9位");
			return "savefial";
		}
		
		//验证邮箱
		Admin checkEmail=adminService.checkEmail(admin.getAdminEmail());
		//验证管理员姓名
		Admin checkName=adminService.checkName(admin.getAdminName());
		if(checkEmail!=null&&admin.getAdminId()==null){
			addFieldError("admin.adminPwd", "注册邮箱已存在");
			return "savefial";
		}
		if (checkName!=null&&admin.getAdminId()==null) {
			addFieldError("admin.adminName", "管理员名称已存在");
			return "savefial";
		}
		System.out.println(11111);
		admin.setIsAdm("Y");
		if(admin.getAdminId()==null||admin.getAdminId().equals("")){
			admin.setStatus(0);
			admin.setType(0);
			admin.setCreated(DateUtils.getCurrentDate());
		}
		admin.setUpdated(DateUtils.getCurrentDate());
		String password="";
		try {
			//密码加密
			password=MD5Utils.GetMD5Code(admin.getAdminPwd());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		admin.setAdminPwd(password);
		if(admin.getAdminId()!=null&&!admin.getAdminId().equals("")){
			this.getAdminService().updateAdmin(admin);
			
				//更新成功，跳转到列表页
				return "adminList";
		
		}else {
			System.err.println(admin.getType());
			adminService.saveAdmin(admin);
			return "adminList";
		}
	}
	/**
	 * 验证邮箱
	 */
	public void checkEmail(){
	    HttpServletResponse response = ServletActionContext.getResponse();  
	    response.setContentType("text/plain;charset=utf-8");  
		Admin checkEmail=adminService.checkEmail(adminEmail);
		String msg="";
		if(checkEmail!=null&&adminId==null){
			msg="该邮箱已被注册！";;
		}else {
			msg="该邮箱可用！";
		}
		JSONArray jsonMsg=JsonUtils.buildMessage(msg);
		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(jsonMsg);
	    out.print(jsonMsg);
		
	}
	/**
	 * 验证用户名称
	 */
	public void checkName(){
		 HttpServletResponse response = ServletActionContext.getResponse();  
	     response.setContentType("text/plain;charset=utf-8");  
		Admin checkName=adminService.checkName(adminName);
		String msg="";
		if(checkName!=null&&adminId==null){
			msg="该邮箱已被注册！";;
			}else {
				msg="该邮箱可用！";
			}
		JSONArray jsonMsg=JsonUtils.buildMessage(msg);
		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(jsonMsg);
	    out.print(jsonMsg);
	}
	/**
	 * 到管理员列表页面
	 * @return
	 */
	public String adminList(){
		return "list";
		
	}
	/**
	 * 得到管理员列表
	 */
	public void getAdmins(){
		int offset=(initPage-1)*pageRow;
		System.err.println(adminName+"====="+status);
		List<Admin> admins=adminService.getAdmins(offset, pageRow, adminName, status,order,sort);
        totalCount=adminService.adminsCount(adminName, status);
        System.err.println("totalCount"+totalCount);
        HttpServletResponse response = ServletActionContext.getResponse();  
	    response.setContentType("text/plain;charset=utf-8");  
		//将结果转换成list，页面直接用ajax进行取出
	    System.err.println(admins);
	    JSONArray adminList=JSONArray.fromObject(admins);
	    //JsonUtils json=new JsonUtils();
		JSONObject jo=JsonUtils.buildJson(adminList, initPage, pageRow, totalCount);
		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(jo);
		out.print(jo);
	}
	/**
	 * 获取某个管理员
	 * @return
	 */
	public String adminEdit(){
		if(adminId!=null){
			admin=adminService.getAdmin(adminId);
			
		}
			return "edit";
		
	}
	/**
	 * 更新张华状态
	 * @return
	 */
	public String updateAdminStatus(){
		boolean flag=this.getAdminService().updateAdminStatus(status, adminId);
		if(flag==true){
			return "adminList";
		}
		return "fail";
		
	}
	/**
	 * 管理员退出
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public String adminLoginOut(){
		ActionContext ac = ActionContext.getContext();
		Map session = ac.getSession();
		session.remove("admin");
		return "Index";
	}
}
